import java.net.*;
import java.io.*;
import java.util.*;

/** ServerTalk2.java and LocalTalk2.java:
    The ServerTalk2.java and LocalTalk2.java send and receive messages as
 objects to each other. The programs have the following features:

	1. The server accepts only one client connection.
	2. ObjectInputStream and ObjectOutputStream are used to send
	   and received object.
	3. It looks like that object put on socket by one side must be
	   read by the other side before another object can be put on
	   the socket.
	4. The readObject() function will always be blocked if no object
	   is available. The function available() cannot be used to test
	   whether there are bytes available for ObjectInputStream object.
*/
   
public class ServerTalk2 {
   public static void main(String args[] ) {

     ObjectOutputStream out ;
     ObjectInputStream in;
     String message;

     try {
 	ServerSocket ssk = new ServerSocket(8900);
	int anum = 1;
	Socket       sk = ssk.accept();

	out = new ObjectOutputStream(sk.getOutputStream());
	in = new ObjectInputStream(sk.getInputStream());

	while ( true ) {
		message = "Server message " + anum ++;
		out.writeObject( message );
		out.flush();

		message = (String) in.readObject();
		System.out.println("Message received by Server: " + message);

		Thread.sleep( (int)(Math.random() * 2000) + 500);
	}
      } catch (Exception e) { e.printStackTrace(); }
   }
}

